#include "peer.h"
#include "tad.h"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

/* VAR GLOBALES */
extern struct peer *hashmap_peers;
extern struct file *hashmap_files;
extern pthread_t peers[NUM_MAX_PEERS];
extern pthread_t tracker;
/****************/


/****************** TAD ***********************/

void add_peer(struct peer *p) {
    //HASH_ADD_STR(hashmap, key, p);
    if(!p) return;
    if(find_peer(p->key)) return;
    
    p->next = hashmap_peers;
    hashmap_peers = p;
}

struct peer *find_peer(char *key) {
    struct peer *s = hashmap_peers;
    
    //HASH_FIND_STR(hashmap, key, s);  
    
    while(s) {
      if(!strcmp(key, s->key))
        break;
      s = s->next;
    }
    
    return s;
}

struct file *add_file(struct file *p, struct file *hashmap_files) {
    if(!p) return hashmap_files;
    if(find_file(p->key, hashmap_files)) return hashmap_files;
    
    p->next = hashmap_files;
    hashmap_files = p;
    return hashmap_files;
}

struct file *find_file(char *key, struct file *hashmap_files) {
    struct file *s = hashmap_files;
       
    while(s) {
      if(!strcmp(key, s->key))
        break;
      s = s->next;
    }
    
    return s;
}

struct file *find_file_subname(char *subname, struct file *hashmap_files) {
    struct file *s = hashmap_files;
       
    while(s) {
      if(!strstr(s->name, subname))
        break;
      s = s->next;
    }
    
    return s;
}

/**********************************************/


void erase(char *buff, int n) {
  int i;
  for(i=0; i<n; i++)
    buff[i] = '\0';
}

char* goto_next_word(char *string, char *cpy[BUF_SIZE]) {
  
  if(*cpy) {
    free(*cpy);
    *cpy = NULL;
  }

  while(*string==' ' && *string!='\0')
    string++;
    
  int i = 0;
  
  while(string[i]!=' ' && string[i]!='\0') i++;
  
  
  *cpy = calloc(sizeof(char), i+1);
  if(!(*cpy)) return NULL;
  
  memcpy(*cpy, string, i);
  (*cpy)[i] = '\0';
  
  string += i;
  
  while(*string==' ' && *string!='\0')
    string++;
  
  return string;
}
